//
//  SelectPrinterViewController.m
//  BluetoothPrint
//
//  Created by wang on 2017/11/3.
//  Copyright © 2017年 wang. All rights reserved.
//

#import "SelectPrinterViewController.h"
#import <ExternalAccessory/ExternalAccessory.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import "Printer.h"
@interface SelectPrinterViewController ()<UITableViewDelegate, UITableViewDataSource,CBCentralManagerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) CBCentralManager *printer;
@property (nonatomic, strong) NSMutableArray<Printer *> *dataArr;

@end

@implementation SelectPrinterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self searchPrinter];
    // Do any additional setup after loading the view from its nib.
}
- (IBAction)searchPrintersClick:(id)sender {
  
    [self.dataArr removeAllObjects];
    
    [self searchPrinter];
    
}
- (void)searchPrinter
{
    if (self.MFI) {
        NSArray *list = [EAAccessoryManager sharedAccessoryManager].connectedAccessories;
        if (list.count == 0) {
            NSLog(@"请您先去蓝牙设置中连接毕索龙打印机,输入0000进行配对");
            return;
        }
        for (EAAccessory *accessory in list) {
            NSString *name = accessory.name.length?accessory.name:@"未命名";
            name = [name componentsSeparatedByString:@"\\"].firstObject;
            NSString *macAddress = [accessory valueForKey:@"macAddress"];
            Printer *model = [Printer new];
            model.name = name;
            model.uuidStr = macAddress;
            [self.dataArr addObject:model];
        }
        [self.tableView reloadData];
        
    }else{
        if (self.printer.state == CBCentralManagerStatePoweredOff){
            //您的蓝牙还未开启
            NSLog(@"您的蓝牙还未开启");
            return;
        }
        
        [self.tableView reloadData];
        [self.printer scanForPeripheralsWithServices:nil options:nil];
    }
}

#pragma mark - CBCentralManagerDelegate

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    if (self.printer.state == CBCentralManagerStatePoweredOn) {
        [self.printer scanForPeripheralsWithServices:nil options:nil];
    }
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    if(peripheral.name.length == 0){
        //去掉没有名字的打印机
        return;
    }
    NSString *name = peripheral.name.length?peripheral.name:@"未命名";
    NSString *uuid_address = peripheral.identifier.UUIDString;
    BOOL add = YES;
//    for (Printer *printer in self.dataArr) {
//        if ([printer.uuidStr isEqualToString:uuid_address]) {
//            add = NO;
//            break;
//        }
//    }
    if (add) {
        Printer *printer = [Printer new];
        printer.uuidStr = peripheral.identifier.UUIDString;
        printer.name = name;
        [self.dataArr addObject:printer];
    }
    [self.tableView reloadData];
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    Printer *printer = self.dataArr[indexPath.row];
    cell.textLabel.text = printer.name;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Printer *printer = self.dataArr[indexPath.row];
    if (self.didSelect) {
        self.didSelect(printer.name,printer.uuidStr);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CBCentralManager *)printer {
    if(_printer == nil) {
        _printer = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    return _printer;
}
- (NSMutableArray *)dataArr
{
    if (_dataArr == nil) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
